<template>
  <div class="img">
    <!-- :data="{ biz: bizPath }" -->
    <!-- :isMultiple="isMultiple" -->
    <a-upload
      @change="handleChange"
      name="file"
      listType="picture-card"
      :multiple="isMultiple"
      :action="uploadAction"
      :fileList="fileList"
      :beforeUpload="beforeUpload"
      :customRequest="customRequest"
      :disabled="disabled"
      @preview="handlePreview"
      :class="[!isMultiple ? 'imgupload' : '', !isMultiple && picUrl ? 'image-upload-single-over' : '']"
    >
      <div class="iconp" v-if="fileList.length < number">
        <a-icon type="plus" />
        <div class="ant-upload-text">{{ text }}</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel()">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getFileAccessHttpUrl } from '@/api/manage'
import axios from 'axios'
import storage from 'store'

const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    let reg = new RegExp('\\\\', 'g')
    path = path.replace(reg, '/')
  }
  return path.substring(path.lastIndexOf('/') + 1)
}
export default {
  name: 'ImageUpload',
  data() {
    return {
      uploadAction: '',
      uploadLoading: false,
      picUrl: false,
      headers: {},
      fileList: [],
      previewImage: '',
      previewVisible: false,
    }
  },
  props: {
    text: {
      type: String,
      required: false,
      default: '上传',
    },
    /*这个属性用于控制文件上传的业务路径*/
    // bizPath: {
    //   type: String,
    //   required: false,
    //   default: 'temp',
    // },
    value: {
      type: [String, Array],
      required: false,
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    isMultiple: {
      type: Boolean,
      required: false,
      default: false,
    },
    number: {
      type: Number,
      required: false,
      default: 0,
    },
    action: {
      type: String,
      required: true,
      default: '',
    },
    idStr: {
      type: String,
      required: false,
      default: '',
    },
  },
  watch: {
    value: {
      handler(val, oldValue) {
        console.log(val, 'val')
        if (val instanceof Array) {
          this.initFileList(val.join(','))
        } else {
          this.initFileList(val)
        }
        if (!val || val.length == 0) {
          this.picUrl = false
        }
      },
      //立刻执行handler
      immediate: true,
    },
  },
  created() {
    console.log(this.value, 'val')
    const token = storage.get(ACCESS_TOKEN)
    this.headers = { Authorization: token, 'Content-Type': 'multipart/form-data' }
  },
  methods: {
    initFileList(paths) {
      if (!paths || paths.length === 0) {
        this.fileList = []
        return
      }
      this.picUrl = true
      let fileList = []
      let arr = paths?.split(',')
      for (var a = 0; a < arr.length; a++) {
        let url = getFileAccessHttpUrl(arr[a])
        fileList.push({
          uid: uidGenerator(),
          name: getFileName(arr[a]),
          status: 'done',
          url: url,
          response: {
            status: 'history',
            message: arr[a],
          },
        })
      }
      this.fileList = fileList
    },
    beforeUpload: function (file) {
      var fileType = file.type
      if (fileType.indexOf('image') < 0) {
        this.$message.warning('请上传图片')
        return false
      }
    },
    customRequest({ file, onProgress, onSuccess }) {
      const formData = new FormData()
      formData.append('file', file)
      formData.append('id', 1)
      axios
        .post(`${window._CONFIG['domianURL']}${this.action}`, formData, {
          method: 'post',
          headers: {
            Authorization: storage.get(ACCESS_TOKEN),
            'Content-Type': 'multipart/form-data',
          },
          onUploadProgress: ({ total, loaded }) => {
            onProgress({ percent: +Math.round((loaded / total) * 100).toFixed(2) }, file)
          },
        })
        .then(({ data: response }) => {
          if (response.code === 200) {
            console.log(response, 'response')
            this.$message.success(response?.msg)
            onSuccess({ fileUrl: response.data.fileName, id: response.data.id })
          } else {
            onSuccess({ fileUrl: null })
            throw new Error(response.msg)
          }
        })
        .catch((err) => {
          this.$message.error(err?.message || '上传失败')
        })
    },
    handleChange(info) {
      console.log(info, 'info')
      setTimeout(() => {
        let fileLists = [...info.fileList]
        if (this.number === 1) {
          fileLists = fileLists.slice(-1)
        }

        if (this.number && typeof +this.number === 'number') {
          fileLists = fileLists.slice(-this.number)
        }
        if (info.file.status === 'done') {
          let idArr = []
          console.log(this.idStr, 'idStr')
          if (this.idStr !== '') {
            let arr = this.idStr?.split(',') || []
            let arr1 = idArr.concat(arr)
            idArr = arr1
            console.log(arr1, 'idArr', arr)
          }
          fileLists.map((i) => {
            idArr.push(i.response.id)
          })
          this.$emit('change', { fileLists, fileUrl: info.file.response.fileUrl, idArr: idArr.toString() })
        }
        this.fileList = fileLists
        console.log(this.fileList, 'this.fileList')
      }, 0)
    },
    // 预览
    handlePreview(file) {
      this.previewImage = file.url || file.thumbUrl
      this.previewVisible = true
    },
    handleCancel() {
      this.close()
      this.previewVisible = false
    },
    close() {},
  },
  model: {
    prop: 'value',
    event: 'change',
  },
}
</script>

<style scoped>
.imgupload .iconp {
  padding: 20px;
}
/* update--end--autor:lvdandan-----date:20201016------for：j-image-upload图片组件单张图片详情回显空白*/

.image-upload-single-over .ant-upload-select {
  display: none;
}
</style>
